﻿using Microsoft.Win32;
using System.Reflection;
using System.Security.Permissions;

//Code from http://www.poppastring.com/HowToAutoStartAnApplicationWithNET.aspx
static class AutoStart {
    private const string APP_NAME = "VistaShades"; //replace this with the name of your application
    private const string REG_ENTRY = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";

    /// <summary>
    /// Enables auto start
    /// </summary>
    public static void EnableAutoStart() {
        RegistryKey key = Registry.CurrentUser.CreateSubKey(REG_ENTRY);
        key.SetValue(APP_NAME, Assembly.GetExecutingAssembly().Location);
    }
    
    /// <summary>
    /// Disables autostart.
    /// </summary>
    public static void DisableAutoStart() {
        
        //this line changed by BTE from original code which used OpenSubKey.  That specifies readonly
        //permissions while Create allows write/delete.
        RegistryKey key = Registry.CurrentUser.CreateSubKey(REG_ENTRY); 
        if (key != null) {
            string val = (string)key.GetValue(APP_NAME);
            if (val != null)                             
                key.DeleteValue(APP_NAME);
        }
    }

    /// <summary>
    /// Checks if auto start is enabled.
    /// </summary>
    public static bool IsAutoStartEnabled {
        get {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(REG_ENTRY);
            if (key == null) {
                return false;
            }

            string val = (string)key.GetValue(APP_NAME);
            if (val == null)
                return false;



            return (val == Assembly.GetExecutingAssembly().Location);
        }
    }

}